package ru.spbsu.electromenu.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.spbsu.electromenu.model.Table;
import ru.spbsu.electromenu.service.TableService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Date: 5/2/11
 * Time: 1:00 AM
 *
 * @author Artem Titov
 */
public class EditTableServlet extends SpringHttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(EditTableServlet.class);
    private TableService tableService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        tableService = getBean("tableService");
        if (tableService == null) {
            logger.error("Failed to instantiate necessary services");
            isValid = false;
            throw new IllegalStateException("Failed to instantiate necessary services");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {

            final String sId = request.getParameter("id");
            try {
                final int id = Integer.parseInt(sId);
                if (request.getParameter("save") != null) {
                    final Table table = new Table();
                    table.setId(id);
                    tableService.put(table);
                } else if (request.getParameter("delete") != null) {
                    tableService.delete(id);
                }
                response.sendRedirect("showTable");
            } catch (NumberFormatException e) {
                logger.error("Failed to parse id " + sId, e);
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } catch (Exception e) {
                logger.error("Failed to save table with id " + sId, e);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IllegalArgumentException e) {
            logger.error("Failed to parse table", e);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}
